package com.gjy.encryption.symmetry;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

/**
 * 工作模式:
 * ECB
 * 填充方式:
 * PKCS5Padding,PKCS7Padding
 *
 * @author 宫静雨
 * @version 1.0
 * @since 2022-11-08 10:07:29
 */
public class IDEACoder {

    // 秘钥算法，56位，bc支持64位
    private static final String KEY_ALGORITHM = "IDEA";
    private static final Integer KEY_SIZE = 128;
    // 加解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "IDEA/ECB/PKCS7Padding";
    private final Key key;

    public IDEACoder() {
        Security.addProvider(new BouncyCastleProvider());
        this.key = initKey();
    }

    public byte[] encrypt(byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public byte[] decrypt(byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Key initKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(KEY_SIZE);
            SecretKey generateKey = keyGenerator.generateKey();
            return new SecretKeySpec(generateKey.getEncoded(),KEY_ALGORITHM);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
